import {
  reqCartList,
  reqDeleteCartById,
  reqUpdateCheckedById
} from '../../api'
const state = {
  cartList: []
}
const mutations = {
  CARTLIST(sate, cartList) {
    sate.cartList = cartList
  }
}
const actions = {
  //获取购物车列表数据
  async getCartList({
    commit
  }) {
    let result = await reqCartList()
    if (result.code == 200) {
      commit('CARTLIST', result.data)
    }
  },
  //删除购物车某一产品
  async deleteCartListBySkuId({
    commit
  }, skuId) {
    let result = await reqDeleteCartById(skuId)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  //修改购物车产品选中状态
  async updateCheckedById({
    commit
  }, {
    skuId,
    isChecked
  }) {
    let result = await reqUpdateCheckedById(skuId, isChecked)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  //删除全部勾选
  deleteAllCheckedCart({
    dispatch,
    getters
  }) {
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach(element => {
      let promise = element.isChecked == 1 ? dispatch('deleteCartListBySkuId', element.skuId) : ''
      PromiseAll.push(promise)
    });


    return Promise.all(PromiseAll)
  },
  //修改全部产品选中状态
  updateAllCartIsChecked({
    dispatch,
    state
  }, isChecked) {
    let promiseAll = []
    state.cartList[0].cartInfoList.forEach(element => {
      let promise = dispatch('updateCheckedById', {
        skuId: element.skuId,
        isChecked
      })
      promiseAll.push(promise)
    })
    return Promise.all(promiseAll)
  }
}
//相当于计算属性，简化数据
const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  },

}
export default ({
  state,
  mutations,
  actions,
  getters
})